<?php
/**
 * Pages Model
 * @author Kirill Egorov 2011
 */
class Model_Page extends Model
{
    protected static $_instance =  null;
    /**
     * @return Model_Page
     */
	static public function getInstance(){
        if(is_null(self::$_instance))
           self::$_instance = new self('page');     
        return self::$_instance;   
    }
    
	/**
     * Get Pages tree
     * @return array
     */
    public function getTreeList(array $fields , $author=false , $publisher=false)
    {    
        /*
         * Add the required fields to the list
         */
         $fields = array_unique(array_merge(array('id','parent_id','order_no','code','menu_title','is_fixed'),$fields));
         $data = $this->getListVc(array('sort'=>'order_no','dir'=>'ASC'), false, false, $fields , $author , $publisher);  
         
         if(empty($data))
             return array();
             
         $ids = Utils::fetchCol('id', $data);
         $vc = Model_Vc::getInstance();
         $maxRevisions = $vc->getLastVersion('page' , $ids);
            
         foreach ($data as $k=>&$v){
            if(isset($maxRevisions[$v['id']]))
                $v['last_version'] = $maxRevisions[$v['id']];
            else
                $v['last_version'] = 0;   
         }unset($v);    
                
         $result = array();
         $deleted = array();
         
          if(empty($data))
               return array();
          
         $tree = new Tree(); 
         
         foreach($data as $value)
             $tree->addItem($value['id'], $value['parent_id'], $value ,$value['order_no']);
         
         return $this->_fillChilds($tree , 0);
    }
    
    /**
     * Fill childs data array for tree panel
     * @param Tree $tree
     * @param mixed $root
     * @return array
     */
    protected function _fillChilds(Tree $tree , $root = 0 )
    {
           $result = array();   
           $childs = $tree->getChilds($root);      
               
           if(empty($childs))
                return array();
                   
           foreach($childs as $k=>$v)
           {
                  $row = $v['data'];                            
                  $obj = new stdClass();
 
                  $obj->id = $row['id'];  
                  $obj->text= $row['menu_title'] . ' <i>('.$row['code'].$this->_storage->get('config_main')->get('urlExtension').')</i>';
                  $obj->expanded= true;
                  $obj->leaf=false;

                  if($row['published']){
                      $obj->qtip = $row['menu_title'] . ' <i>('.$row['code'].$this->_storage->get('config_main')->get('urlExtension').')</i> published';
                      $obj->iconCls = 'pagePublic';
                  } else {
                      $obj->qtip = $row['menu_title'] . ' <i>('.$row['code'].$this->_storage->get('config_main')->get('urlExtension').')</i> not published';
                      $obj->iconCls = 'pageHidden';
                  }
                  
                   if($row['is_fixed'])
                       $obj->allowDrag = false;
                       
                   $cld= array();
                   if($tree->hasChilds($row['id']))
                      $cld = $this->_fillChilds($tree ,  $row['id']);
                       
                   $obj->children=$cld;                                            
                   $result[] = $obj;
           }            
          return $result;     
    }
    
    /**
     * Update pages order_no
     * @param array $data
     */
    public function updateSortOrder(array $sortedIds)
    {  
            $i=0;
            foreach ($sortedIds as $v){
            	$obj = new Db_Object($this->_name, intval($v));
				$obj->set('order_no', $i);
				$obj->save();
				
                $i++;
            }
    }
    
    /**
     * Check if page code exists
     * @param unknown_type $code
     */
     public function codeExists($code)
     {
          $db = Store_Local::getInstance()->get('db');  
          return  $this->_db->fetchOne($this->_db->select()
                                ->from($this->table() , array('count'=>'COUNT(*)'))
                                ->where('code = ?' , $code)
                  );
    }
    
    /**
     * Get topic item ID by its code
     * @param string $code
     * @return integer;
     */
    public function getIdByCode($code) 
    {
         $recId = $this->_db->fetchOne(
                $this->_db->select()
                          ->from($this->table(), array('id'))
                          ->where('code =?',$code)
         );
         return intval($recId);              
    }
    /**
     * Get page data by code
     * @param string $code
     * @return array  
     */
    public function getByCode($code)
    {
    	 $code = Filter::filterValue('pagecode', $code);
    	 
    	 $hash = self::getCodeHash($code);
    	 $data = false;
    	 
    	 if($this->_dataCache && $data = $this->_dataCache->load($hash))
    	 	return $data;

    	 $sql = $this->_db->select()->from($this->table())->where('code =?', $code);
    	 $data = $this->_db->fetchRow($sql);
    	 
    	 if(empty($data))
    	 	return array();
    	 	
    	 if($this->_dataCache)
    	 	$this->_dataCache->save($data,$hash);
 
    	 return $data;
    }
    /**
     * Get hash for pagecode
     * @param string $code
     */
    static public function getCodeHash($code){
    	return md5('page_'.$code);
    }
    /**
     * Reset childs elements set parent 0
     * @param page $id
     */
    public function resetChilds($id)
    {
    	$obj = new Db_Object($this->_name, intval($id));
		$obj->set('parent_id', 0);
		$obj->save();
    }
    
    /**
     * Get item data by its code
     * @param string $code
     * @return array
     */
    public function getItemByCode($code)
    {
       $code = Filter::filterValue('pagecode', $code);
       $cache = Application::dataCache();
       if($cache && $data = $cache->load(self::getCodeHash($code)))
       		return $data;
       		
       		
       $data = $this->_db->fetchRow(
			        $this->_db->select()
			                ->from($this->table())
			                ->where('`code` = ?' ,$code)
		);
    }
}